package by.grsu.pochebut.webpage.client;

import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import by.grsu.pochebut.entity.Client;
import by.grsu.pochebut.interf.InterfClient;
import by.grsu.pochebut.webpage.MyPage;


@SuppressWarnings("serial")
public class ListClientPage extends MyPage {

	@SpringBean
	private InterfClient daoClient;

	public ListClientPage() {
		super();
		// retrieve all objects
		final List<Client> clients = daoClient.findAll();

		// add "list" component and provide list of items which should be
		// rendered
		add(new ListView<Client>("clients", clients) {

			@Override
			protected void populateItem(final ListItem<Client> item) {
				final Client client = item.getModelObject();
				// add "labels" to display each property of the item
				item.add(new Label("name", client.getName()));
				item.add(new Label("passport", client.getPassport()));

				// add link which will forward to the "edit" page
				item.add(new Link<Client>("editlink", new Model<Client>(client)) {
					@Override
					public void onClick() {
						setResponsePage(new EditClientPage(client));
					}
				});

				// add "link" which removes item from database and reload the
				// page
				item.add(new Link<Client>("deletelink", new Model<Client>(client)) {
					@Override
					public void onClick() {
						daoClient.delete(getModelObject().getId());
						setResponsePage(ListClientPage.class);
					}
				});
			}

		});

		// redirect to the "edit" page using "empty" model to create new item as
		// result
		add(new Link<Client>("createLink", new Model<Client>(new Client())) {
			@Override
			public void onClick() {
				setResponsePage(new EditClientPage(getModelObject()));
			}
		});

	}
}
